package com.southminority.ethnic.controller.user;

import com.southminority.ethnic.common.context.UserContext;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.common.util.AdminAuthUtil;
import com.southminority.ethnic.controller.user.vo.*;
import com.southminority.ethnic.pojo.User;
import com.southminority.ethnic.service.user.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "用户模块",description ="用户模块" )
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param loginReqVo
     * @return
     */
    @Operation(summary = "登录")
    @PostMapping("/pagekey")
    public R<User> login(@RequestBody LoginReqVo loginReqVo) {
        try {
            log.info("用户登录，内容：{}", loginReqVo.toString());
            return R.ok(userService.login(loginReqVo.getEmail(), loginReqVo.getPassword()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    @Operation(summary = "获取注册验证码")
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody RegisterReqVo reqVo) {
        try {
            return R.ok(userService.getYzm(reqVo.getEmail()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //注册
    @Operation(summary = "注册")
    @PostMapping("/logon")
    public R<Boolean> logon(@RequestBody LogonReqVo reqVo) {
        try {
            return R.ok(userService.logon(
                    reqVo.getEmail(),
                    reqVo.getPassword(),
                    reqVo.getPasswordAgein(),
                    reqVo.getUsername(),
                    reqVo.getCode()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    //忘记密码验证码
    @Operation(summary = "获取忘记密码证码")
    @PostMapping("/forgetRegister")
    public R<Boolean> forgetRegister(@RequestBody RegisterReqVo reqVo) {
        try {
            return R.ok(userService.forgetYZM(reqVo.getEmail()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //忘记密码-》修改密码
    @Operation(summary = "忘记密码-》修改密码")
    @PostMapping("/forget")
    public R<Boolean> forget(@RequestBody ForgetReqVo reqVo) {
        try {
            return R.ok(userService.forget(reqVo.getEmail(),reqVo.getNewPassword(),reqVo.getCode()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    //查看token是否过期，并合理续token
    @Operation(summary = "查看token是否过期，并合理续token")
    @PostMapping("/checkToken")
    public R<String> checkToken(@RequestBody CheckTokenReqVo reqVo) {
        try {
            log.info("检查token是否过期，并合理续token，内容：{}", reqVo.toString());
            return R.ok(userService.checkToken(reqVo.getToken()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 检查当前用户状态
     */
    @GetMapping("/current")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的信息")
    public R<Map<String, Object>> getCurrentUser() {
        User currentUser = UserContext.getCurrentUser();
        
        Map<String, Object> result = new HashMap<>();
        
        if (currentUser == null) {
            result.put("isLoggedIn", false);
            result.put("message", "用户未登录");
            return R.ok(result);
        }
        
        result.put("isLoggedIn", true);
        result.put("userId", currentUser.getId());
        result.put("username", currentUser.getUsername());
        result.put("email", currentUser.getEmail());
        result.put("userType", currentUser.getUserType());
        result.put("userTypeDescription", AdminAuthUtil.getUserTypeDescription(currentUser.getUserType()));
        result.put("isAdmin", AdminAuthUtil.isAdmin());
        result.put("isSuperAdmin", AdminAuthUtil.isSuperAdmin());
        result.put("isNormalAdmin", AdminAuthUtil.isNormalAdmin());
        result.put("isNormalUser", AdminAuthUtil.isNormalUser());
        
        return R.ok(result);
    }

    /**
     * 测试权限验证
     */
    @GetMapping("/test-permission")
    @Operation(summary = "测试权限验证", description = "测试当前用户的权限状态")
    public R<Map<String, Object>> testPermission() {
        User currentUser = UserContext.getCurrentUser();
        
        Map<String, Object> result = new HashMap<>();
        result.put("currentUser", currentUser != null ? currentUser.getUsername() : "未登录");
        result.put("userType", currentUser != null ? currentUser.getUserType() : null);
        result.put("userTypeDescription", AdminAuthUtil.getUserTypeDescription(currentUser != null ? currentUser.getUserType() : null));
        result.put("isAdmin", AdminAuthUtil.isAdmin());
        result.put("isSuperAdmin", AdminAuthUtil.isSuperAdmin());
        result.put("isNormalAdmin", AdminAuthUtil.isNormalAdmin());
        result.put("isNormalUser", AdminAuthUtil.isNormalUser());
        result.put("hasPermission1", AdminAuthUtil.hasPermission(1));
        result.put("hasPermission2", AdminAuthUtil.hasPermission(2));
        
        return R.ok(result);
    }

    @GetMapping("/logout/{token}")
    @Operation(summary = "退出登录")
    public R<Boolean> logout(@PathVariable String token) {
        try {
            return R.ok(userService.logout(token));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    @Operation(summary = "根据token获取用户信息")
    @GetMapping("/getUserByToken/{token}")
    public R<User> getUserByToken(@PathVariable String token) {
        try {
            return R.ok(userService.getUserByToken(token));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    //根据旧密码去修改新密码
    @Operation(summary = "根据旧密码去修改新密码")
    @PostMapping("/updatePassword")
    public R<Boolean> updatePassword(@RequestBody UpdatePasswordReqVo reqVo) {
        try {
            return R.ok(userService.updatePasswordFromOldPassword(reqVo.getOldPassword(),reqVo.getNewPassword()));
        }catch (Exception e){
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

}
